package helper

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"strings"
)

//16进制数组转16进制字符串
func HexToHexStr(buf []byte) string {
	len := len(buf)
	str := ""
	for i := 0; i < len; i++ {
		if i == 0 {
			str = fmt.Sprintf("%02X", buf[i])
		} else {
			str += fmt.Sprintf(" %02X", buf[i])
		}
	}
	return str
}

//ReadComMapping 读取com口映射
func ReadComMapping(com string) (string, error) {
	coms := make(map[string]string)
	bt, err := ioutil.ReadFile("/opt/xbrother/xtemplates/config_sys_com.json")
	if err != nil {
		return "", err
	}
	err = json.Unmarshal(bt, &coms)
	if err != nil {
		return "", err
	}
	for k, v := range coms {
		if strings.ToLower(v) == strings.ToLower(com) {
			return k, nil
		}
	}
	return "", errors.New(fmt.Sprintf("%s is not found in path:/opt/xbrother/xtemplates/config_sys_com.json", com))
}

//IntToBytes 将int型值转换为指定长度的byte切片，len不应该超过8
func IntToBytes(source, len int) []byte {
	target := make([]byte, len)

	for i := 0; i < len; i++ {
		target[i] = byte(uint64(source) >> ((len - i - 1) * 8))
	}

	return target
}
